// ignore_for_file: use_build_context_synchronously, prefer_typing_uninitialized_variables, deprecated_member_use
import 'dart:math';
import 'package:bot_toast/bot_toast.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:wallpaper/api/author.dart';
import 'package:wallpaper/generated/l10n.dart';

class UpdateApk {
  var loadingBot;

  Future updateApk(BuildContext context, {bool displayTips = false}) async {
    try {
      Response res = await updateApp();
      PackageInfo packageInfo = await PackageInfo.fromPlatform();
      String version = packageInfo.version; // 获取版本号
      if (version != res.data['version']) {
        loadingBot = BotToast.showCustomLoading(
            backgroundColor: Colors.black.withOpacity(0.35),
            toastBuilder: (cancel) {
              final theme = Theme.of(context);
              final primary = theme.colorScheme.primary;
              final isDark = theme.brightness == Brightness.dark;
              return Center(
                child: Material(
                  color: Colors.transparent,
                  child: Container(
                    width: min(300, (MediaQuery.of(context).size.width - 30)),
                    padding: const EdgeInsets.symmetric(
                        horizontal: 24, vertical: 24),
                    decoration: BoxDecoration(
                      color: isDark ? theme.cardColor : Colors.white,
                      borderRadius: BorderRadius.circular(10),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.12),
                          blurRadius: 32,
                          offset: Offset(0, 8),
                        ),
                      ],
                    ),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Icon(Icons.system_update_alt_rounded,
                                color: primary, size: 28),
                            SizedBox(width: 10),
                            Text(S.of(context).s15,
                                style: TextStyle(
                                    fontSize: 20,
                                    fontWeight: FontWeight.bold,
                                    color: primary)),
                            Spacer(),
                            Container(
                              decoration: BoxDecoration(
                                color: Colors.grey.withOpacity(0.12),
                                shape: BoxShape.circle,
                              ),
                              child: IconButton(
                                icon: Icon(Icons.close_rounded,
                                    color: Colors.grey[600]),
                                onPressed: () {
                                  loadingBot();
                                },
                              ),
                            ),
                          ],
                        ),
                        SizedBox(height: 8),
                        Divider(
                            height: 1,
                            thickness: 1,
                            color: theme.dividerColor.withOpacity(0.15)),
                        SizedBox(height: 12),
                        Row(
                          children: [
                            Text(S.of(context).s27,
                                style: TextStyle(
                                    fontSize: 15, color: theme.hintColor)),
                            Text('${res.data['version']}',
                                style: TextStyle(
                                    fontSize: 15,
                                    color: primary,
                                    fontWeight: FontWeight.w600)),
                          ],
                        ),
                        SizedBox(height: 10),
                        Text(S.of(context).s28,
                            style: TextStyle(
                                fontSize: 15,
                                fontWeight: FontWeight.w500,
                                color: theme.textTheme.bodyLarge?.color)),
                        SizedBox(height: 6),
                        Container(
                          constraints: BoxConstraints(maxHeight: 120),
                          child: ListView.separated(
                            shrinkWrap: true,
                            itemCount: res.data['update'].length,
                            separatorBuilder: (context, idx) =>
                                SizedBox(height: 6),
                            itemBuilder: (context, index) {
                              return Row(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Container(
                                    margin: EdgeInsets.only(top: 2),
                                    child: CircleAvatar(
                                      radius: 10,
                                      backgroundColor:
                                          primary.withOpacity(0.13),
                                      child: Icon(Icons.check_circle_rounded,
                                          color: primary, size: 16),
                                    ),
                                  ),
                                  SizedBox(width: 8),
                                  Expanded(
                                    child: Text(
                                      '${index + 1}. ${res.data['update'][index]}',
                                      style: TextStyle(
                                          fontSize: 14,
                                          color: theme
                                              .textTheme.bodyMedium?.color),
                                    ),
                                  ),
                                ],
                              );
                            },
                          ),
                        ),
                        SizedBox(height: 18),
                        Row(
                          children: [
                            Expanded(
                              child: ElevatedButton(
                                style: ElevatedButton.styleFrom(
                                  backgroundColor: primary,
                                  foregroundColor: Colors.white,
                                  shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(18)),
                                  padding: EdgeInsets.symmetric(
                                      horizontal: 22, vertical: 10),
                                  elevation: 0,
                                ),
                                onPressed: () async {
                                  if (await canLaunchUrl(
                                      Uri.parse(res.data['url']))) {
                                    await launchUrl(Uri.parse(res.data['url']));
                                  } else {
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      SnackBar(content: Text(res.data['url'])),
                                    );
                                  }
                                  loadingBot();
                                },
                                child: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Icon(
                                      Icons.download_rounded,
                                      size: 18,
                                      color: Colors.white,
                                    ),
                                    SizedBox(width: 6),
                                    Text(S.of(context).s16,
                                        style: TextStyle(
                                            fontWeight: FontWeight.bold)),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              );
            });
      }
      if (version == res.data['version'] && displayTips) {
        BotToast.showText(text: '当前已是最新版本');
      }
    } catch (e) {
      debugPrint('Update APK Error: $e');
    }
  }
}
